<template>
  <div>
    <BasicTable @register="registerTable">
      <!-- <template #form-custom> custom-slot </template> -->
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'serviceRecordType' || column.key === 'type'">
          <div class="flex justify-center">
            <div
              :style="{
                background:
                  record[`${column.key}`] === 2
                    ? '#ff4a4a'
                    : record[`${column.key}`] === 1
                      ? '#fff050'
                      : record[`${column.key}`] === 0
                        ? '#7bfd53'
                        : record[`${column.key}`] === -1
                          ? '#ffffff'
                          : '#000000',
                width: '20px',
                height: '20px',
                borderRadius: '50%',
              }"
            ></div>
          </div>
        </template>

        <template v-if="column.key === 'serviceRecord'">
          <TableAction
            :actions="[
              {
                label: '查看',
                onClick: handleShowServiceRecord.bind(null, record),
              },
            ]"
          />
        </template>
        <template v-if="column.key === 'returnOfGoods'">
          <span>{{ record.returnOfGoods === 1 ? '否' : '是' }}</span>
        </template>
        <template v-if="column.key === 'action'">
          <TableAction
            :actions="[
              {
                label: '编辑',
                onClick: handleEdit.bind(null, record),
              },
              {
                label: '详情',
                onClick: handleDetail.bind(null, record),
              },
              {
                label: '退货',
                onClick: handleReturnGoods.bind(null, record),
                disabled: record.returnOfGoods === 0,
              },
              {
                label: '办结',
                onClick: handleConclude.bind(null, record),
                disabled: record.isCompletion === 1,
              },
              {
                label: '删除',
                onClick: handleDelete.bind(null, record),
                ifShow: userStore.getUserInfo.avatar === '管理员',
              },
            ]"
          />
        </template>
      </template>
      <template #toolbar>
        <div class="flex">
          <a-button
            type="primary"
            class="flex items-center"
            @click="
              openDrawer(true, {
                title: '添加',
              })
            "
          >
            <PlusOutlined />
            添加
          </a-button>
          <a-button class="ml-2 flex items-center" @click="openModal(true)">
            <DeliveredProcedureOutlined />
            导入
          </a-button>
          <Tooltip
            v-if="userStore.getUserInfo.avatar === '管理员'"
            title="默认导出全部数据"
            class="ml-2"
          >
            <a-button class="flex items-center" @click="exportXlsx">
              <DeliveredProcedureOutlined />
              导出
            </a-button>
          </Tooltip>
        </div>
      </template>
    </BasicTable>
    <Drawer @register="register" @next="handleComplete" />
    <ExportModal @register="registerModal" @next="handleComplete" />
    <returnModal @register="registerReturnModal" @next="handleComplete" />
  </div>
</template>
<script lang="ts" setup>
  import { DeliveredProcedureOutlined, PlusOutlined } from '@ant-design/icons-vue';
  import { Tooltip } from 'ant-design-vue';
  import { onMounted, ref } from 'vue';
  import { useRouter } from 'vue-router';

  import {
    getManagementDelete,
    getManagementExcelExport,
    getManagementSearch,
    handleCompletion,
  } from '@/api/page/manage_account';
  import { useDrawer } from '@/components/Drawer';
  // import { jsonToSheetXlsx } from '@/components/Excel';
  import { useModal } from '@/components/Modal';
  import { BasicTable,  TableAction, useTable } from '@/components/Table';
  import { useMessage } from '@/hooks/web/useMessage';
  import { useUserStore } from '@/store/modules/user';

  import Drawer from './component/Drawer.vue';
  import ExportModal from './component/ExportModal.vue';
  import returnModal from './component/returnModal.vue';
  import { getBasicColumns, getFormConfig } from './data';
  // const checkedKeys = ref<Array<string | number>>([]);
  const router = useRouter();
  const [registerModal, { openModal }] = useModal();
  const { createConfirm, createMessage } = useMessage();
  const [register, { openDrawer: openDrawer }] = useDrawer();
  const [registerReturnModal, { openModal: openReturnModal }] = useModal();
  const userStore = useUserStore();
  async function apiList(params) {
    const res = await getManagementSearch(params);
    if (res.code === 1000) {
      list.value = res.obj;
      return res.obj;
    }
    return [];
  }

  const list = ref<any[]>([]);
  onMounted(async () => {
    const schemas = await getFormConfig();
    setProps({
      formConfig: {
        labelWidth: 100,
        autoAdvancedLine: 4,
        schemas,
      },
    });
  });
  const [registerTable, { setTableData, setProps }] = useTable({
    // dataSource: list.value,
    api: apiList,
    columns: getBasicColumns,
    useSearchForm: true,
    showTableSetting: true,
    showIndexColumn: false,
    rowKey: 'id',
    rowSelection: {
      type: 'checkbox',
      // selectedRowKeys: checkedKeys as any,
      // onSelect,
      // onSelectAll,
    },
    actionColumn: {
      title: '操作',
      dataIndex: 'action',
      fixed: 'right',
      width: 260,
    },
  });

  function handleShowServiceRecord(record) {
    router.push({
      path: '/manageAccount',
      query: {
        id: record.id,
      },
    });
  }

  function handleEdit(record) {
    openDrawer(true, {
      title: '编辑',
      record,
      info: 'Info',
    });
  }
  function handleDetail(record) {
    openDrawer(true, {
      title: '详情',
      record,
      info: 'Info',
      details: 'details',
    });
  }
  function handleDelete(record) {
    createConfirm({
      iconType: 'info',
      title: () => '删除提醒',
      content: () => '确定要删除选中内容吗',
      onOk: () => {
        getManagementDelete({ id: record.id }).then((res) => {
          if (res.code === 1000) {
            createMessage.success('删除成功！');
            handleGetManagementSearch();
          } else {
            createMessage.error('删除失败，请重试！');
          }
        });
      },
    });
  }
  function handleReturnGoods(record) {
    openReturnModal(true, {
      record,
    });
  }
  function handleConclude(record) {
    createConfirm({
      iconType: 'info',
      title: () => '办结提醒',
      content: () => '确定要办结该内容吗',
      onOk: () => {
        handleCompletion({ id: record.id }).then((res) => {
          if (res.code === 1000) {
            createMessage.success('办结成功！');
            handleGetManagementSearch();
          } else {
            createMessage.error('办结失败，请重试！');
          }
        });
      },
    });
  }
  async function handleGetManagementSearch() {
    const data = await getManagementSearch({});
    if (data.code === 1000) {
      setTableData(data.obj);
      list.value = data.obj;
    }
  }
  // onMounted(async () => {
  //   handleGetManagementSearch();
  // });
  // 导出
  const exportXlsx = async () => {
    const res = await getManagementExcelExport();
    const fileUrl = window.URL.createObjectURL(new Blob([res.data]));
    const a = document.createElement('a');
    a.style.display = 'none';
    a.href = fileUrl;
    a.setAttribute('download', '客户管理列表.xlsx');
    document.body.appendChild(a);
    a.click();
    window.URL.revokeObjectURL(a.href);
    document.body.removeChild(a);
  };

  function handleComplete() {
    handleGetManagementSearch();
  }
</script>
